package net.takela.acl.auth;

import net.takela.acl.auth.dao.AclDao;
import net.takela.acl.auth.filter.AclCheckFilter;
import net.takela.acl.auth.service.AclService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

@Configuration
public class AclCheckAutoConfig {
    @Bean
    @ConfigurationProperties(prefix = "auth.acl")
    public AclProperties securityProperties(){
        return new AclProperties();
    }

    @Bean
    @ConditionalOnBean(AclDao.class)
    public AclService aclService(AclDao aclDao){
        return new AclService(aclDao);
    }
    @Bean
    @ConditionalOnBean(AclService.class)
    public AclCheckFilter aclCheckFilter(AclService aclService, AclProperties aclProperties){
        return new AclCheckFilter(aclService, aclProperties);
    }
    @Bean
    @ConditionalOnBean(AclCheckFilter.class)
    @ConditionalOnMissingBean(name = "aclCheckFilterRegistrationBean")
    public FilterRegistrationBean<AclCheckFilter> aclCheckFilterRegistrationBean(AclCheckFilter aclCheckFilter ) {
        FilterRegistrationBean<AclCheckFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(aclCheckFilter);
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE+1);// 指定要应用过滤器的 URL 模式
        return registrationBean;
    }
}
